// @ts-check
const { defaultEquals } = require('../util');
const { Node } = require('./models/linked-list-models');

class LinkedList {
  constructor(equalsFn = defaultEquals) {
    this.count = 0;
    this.head = undefined;
    this.equalsFn = equalsFn;
  }

  // 向后链接一个节点
  push(element) {
    const node = new Node(element);
    let current;
    if (this.head == null) {
      this.head = node;
    } else {
      current = this.head;
      while (current.next != null) {
        current = current.next;
      }
      current.next = node;
    }
    this.count++;
  }

  // 获取指定的节点并返回节点
  getElementAt(index) {
    // 检查越界值
    if (index >= 0 && index < this.count) {
      let currentNode = this.head; // 当前节点设置为第一个
      for (let i = 0; i < index; i++) {
        currentNode = currentNode.next; // 每次循环  当前节点往后移动一位
      }
      return currentNode;
    }
    return undefined;
  }

  // 根据给定元素的位置 来移除节点
  removeAt(index) {
    let current = this.getElementAt(index);
    if (index === 0) {
      this.head = current.next;
    } else {
      const previous = this.getElementAt(index - 1);
      current = previous.next;
      // 将上一个的next和目前的next链接  跳过current
      // 这个current丢弃在计算机内存中 等着被垃圾回收器回收
      previous.next = current.next;
    }
    this.count--;
    return current.element; // TOASK  这里如果返回的是current 是不是就不会被垃圾回收器回收？
  }

  // 向指定节点插入元素
  insert(element, index) {
    // 检查边界值
    if (index >= 0 && index <= this.count) {
      const node = new Node(element);
      if (index === 0) {
        const current = this.head;
        node.next = current;
        this.head = node;
      } else {
        const previous = this.getElementAt(index - 1);
        const current = previous.next;
        previous.next = node;
        node.next = current;
      }
      this.count++;
      return true;
    }
    return false;
  }

  // 找到第一个匹配的节点，返回元素位置，否则返回-1
  indexOf(element) {
    let current = this.head;
    for (let i = 0; i < this.count && current != null; i++) {
      if (this.equalsFn(current.element, element)) {
        return i;
      }
      current = current.next;
    }
    return -1;
  }

  // 根据要移除的元素 来移除节点
  remove(element) {
    const index = this.indexOf(element);
    return this.removeAt(index);
  }

  size() {
    return this.count;
  }

  isEmpty() {
    return this.size() === 0;
  }

  getHead() {
    return this.head;
  }

  toString() {
    if (this.head == null) {
      return '';
    }
    let returnStr = `${this.head.element}`;
    let current = this.head.next;
    for (let i = 1; i < this.size() && current != null; i++) {
      returnStr = `${returnStr},${current.element}`;
      current = current.next;
    }
    return returnStr;
  }
}

exports.LinkedList = LinkedList;
